import cache from '@/utils/cache'
import { Login } from '@/api/login'
import { GetInfo, UpdateInfo, UpdateInfoByHeadImg, GetGradeList } from '@/api/api'

export default {
    namespaced: true,
    state: {
        token: '',
        userInfo: {},  // 用户信息
        DLBvalue: '',     // 当前阅读新闻获取的DLB奖励
        gradeList: []
    },
    getters: {
        token: state => {
            return state.token
		},
        userInfo: state => {
            return state.userInfo
		},
		DLBvalue: state => {
            return state.DLBvalue
        },
        gradeList: state => {
            return state.gradeList
		}
    },
    mutations: {
        set_token(state, val) {
            state.token = val
            cache.setLocal('token', val)
        },
        set_DLBvalue(state, val) {
            state.DLBvalue = val
            cache.setSession('DLBvalue', val)
        },
        set_userInfo(state, val) {
            state.userInfo = val
            cache.setSession('userInfo', val)
		},
        set_gradeList(state, val) {
            state.gradeList = val
            cache.setSession('gradeList', val)
		}
    },
    actions: {
        // 登录
        async get_login_data({ commit }, params) {
            let res = await Login(params)
            if(res.code == 200){
                commit('set_token', res.data.token)
                commit('set_userInfo',res.data)
            }
            return res
        },
        
        // 获取用户信息缓存
        get_userInfo_cache() {
            let data = JSON.parse(cache.getSession('userInfo'))
            return data
        },

        // 获取用户信息
        async get_userInfo_data({ commit }) {
            let {data} = await GetInfo()
            commit('set_userInfo', data)
            return data
		},
		
		// 修改用户信息
        async post_userInfo_data({ commit }, params) {
			let res = await UpdateInfo(params)
			commit('set_userInfo', res)
            return res
		},
		
		// 修改用户头像
        async post_userInfoByHeadImg_data({ commit }, formData) {
			let res = await UpdateInfoByHeadImg(formData)
			commit('set_userInfo', res)
            return res
        },

        // 获取用户等级缓存
        get_gradeList_cache() {
            let data = JSON.parse(cache.getSession('gradeList'))
            return data
        },

        // 获取用户等级
        async get_gradeList_data({ commit }) {
			let {data} = await GetGradeList()
            commit('set_gradeList', data)
            return data
        }
    }
}